package com.leo.ibatis.demo.dao.ibatis;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.util.Assert;

import com.leo.ibatis.demo.criteria.SupplierCriteria;
import com.leo.ibatis.demo.dao.SupplierDao;
import com.leo.ibatis.demo.domain.Supplier;
import com.leo.ibatis.demo.util.Paging;

public class SupplierDaoImpl extends SqlMapClientDaoSupport implements SupplierDao {

	public void insert(Supplier supplier) throws DataAccessException {
		getSqlMapClientTemplate().insert("Supplier.insert", supplier);
	}

	public int update(Supplier supplier) throws DataAccessException {
		int actualRowsAffected = 1;

		getSqlMapClientTemplate().update("Supplier.update", supplier, actualRowsAffected);

		return actualRowsAffected;
	}

	public int delete(int suppid) throws DataAccessException {
		int actualRowsAffected = 1;

		getSqlMapClientTemplate().delete("Supplier.delete", new Integer(suppid), actualRowsAffected);

		return actualRowsAffected;
	}

	public Supplier select(int suppid) throws DataAccessException {
		return (Supplier) getSqlMapClientTemplate().queryForObject("Supplier.select", new Integer(suppid));
	}

	@SuppressWarnings("unchecked")
	public List<Supplier> list(SupplierCriteria supplierCriteria) throws DataAccessException {
		Assert.notNull(supplierCriteria, "supplierCriteria must not be null");
		
		return getSqlMapClientTemplate().queryForList("Supplier.list", supplierCriteria);
	}

	@SuppressWarnings("unchecked")
	public List<Supplier> listOnPage(SupplierCriteria supplierCriteria) throws DataAccessException {
		Assert.notNull(supplierCriteria, "supplierCriteria must not be null");
		Assert.notNull(supplierCriteria.getPaging(), "paging must not be null");
		
		int totalResults = count(supplierCriteria);
		Paging paging = supplierCriteria.getPaging();
		paging.setTotalResults(totalResults);
		
		return getSqlMapClientTemplate().queryForList("Supplier.list", supplierCriteria, paging.getFirstResult(), paging.getMaxResults());
	}

	public int count(SupplierCriteria supplierCriteria) throws DataAccessException {
		Assert.notNull(supplierCriteria, "supplierCriteria must not be null");
		
		return ((Integer) getSqlMapClientTemplate().queryForObject("Supplier.count", supplierCriteria)).intValue();
	}

}
